package com.controller;

import com.annotation.IgnoreAuth;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dao.ChanpinxinxiDao;
import com.entity.ChanpinchoujianEntity;
import com.entity.ChanpinxinxiEntity;
import com.entity.GongzuorenyuanEntity;
import com.entity.view.ChanpinxinxiView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.service.ChanpinchoujianService;
import com.service.ChanpinxinxiService;
import com.service.GongyingshangService;
import com.service.GongzuorenyuanService;
import com.utils.MPUtil;
import com.utils.PageUtils;
import com.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 农产品信息
 * 后端接口
 *
 * @author
 * @email
 * @date 2030-02-14 10:54:18
 */
@RestController
@RequestMapping("/chanpinxinxi")
public class ChanpinxinxiController {
    @Autowired
    private ChanpinxinxiService chanpinxinxiService;

    @Autowired
    private GongyingshangService gongyingshangService;

    @Autowired
    private ChanpinchoujianService chanpinchoujianService;
    @Autowired
    private GongzuorenyuanService gongzuorenyuanService;
    @Autowired
    private ChanpinxinxiDao baseMapper;


    @PostMapping("/choujian")
    public R choujian(@RequestParam Long id, @RequestParam String chanpinmingcheng, HttpServletRequest request) {
        //查询商品信息
        ChanpinxinxiEntity chanpinxinxiEntity = chanpinxinxiService.selectById(id);
        if (chanpinxinxiEntity == null) {
            return R.error("商品不存在");
        }
        ChanpinchoujianEntity chanpinchoujian = new ChanpinchoujianEntity();
        chanpinchoujian.setBianhao(new Date().getTime() + new Double(Math.floor(Math.random() * 1000)).longValue() + "");
        chanpinchoujian.setChoujianzhuangtai("抽检中");
        Long userId = (Long) request.getSession().getAttribute("userId");
        GongzuorenyuanEntity u = gongzuorenyuanService.selectById(userId);
        chanpinchoujian.setChoujianren(u.getXingming());
        chanpinchoujian.setCreateTime(new Date());
        chanpinchoujian.setChanpinmingcheng(chanpinmingcheng);
        chanpinchoujianService.insert(chanpinchoujian);
        return R.ok();
    }


    @PostMapping("/shengchengerweima")
    public R shengchengerweima(@RequestParam Long id) {
        //查询商品信息
        ChanpinxinxiEntity chanpinxinxiEntity = chanpinxinxiService.selectById(id);
        if (chanpinxinxiEntity == null) {
            return R.error("商品不存在");
        }

        String text = "http://localhost:8080/traceability/chanpinxinxi/detail/" + id;
        String filePath = new Date().getTime() + "qrcode.png";
        int width = 300;
        int height = 300;
        try {
            generateQRCode(text, filePath, width, height);
            System.out.println("QR Code generated successfully.");
        } catch (WriterException | IOException e) {
            System.out.println("Could not generate QR Code: " + e.getMessage());
        }
        chanpinxinxiEntity.setErweima("upload/" + filePath);
        chanpinxinxiService.updateById(chanpinxinxiEntity);
        return R.ok();
    }


    public static void generateQRCode(String text, String filePath, int width, int height)
            throws WriterException, IOException {
        Map<EncodeHintType, Object> hintMap = new HashMap<>();
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        hintMap.put(EncodeHintType.MARGIN, 1);
        hintMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hintMap);

//        String path1 = "C:\\project\\food-traceability\\src\\main\\resources\\static\\upload\\";
//        String path2 = "C:\\project\\food-traceability\\target\\classes\\static\\upload\\";
        String path1 = "E:\\Temp\\test\\traceability\\src\\main\\resources\\static\\upload\\";
        String path2 = "E:\\Temp\\test\\traceability\\target\\classes\\static\\upload\\";

        Path path = FileSystems.getDefault().getPath(path1 + filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
        Path path3 = FileSystems.getDefault().getPath(path2 + filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path3);
    }

    /**
     * 后端列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params, ChanpinxinxiEntity chanpinxinxi,
                  HttpServletRequest request) {
        EntityWrapper<ChanpinxinxiEntity> ew = new EntityWrapper<ChanpinxinxiEntity>();

        PageUtils page = chanpinxinxiService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, chanpinxinxi), params), params));
        return R.ok().put("data", page);
    }

    /**
     * 前端列表
     */
    @IgnoreAuth
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params, ChanpinxinxiEntity chanpinxinxi,
                  HttpServletRequest request) {
        EntityWrapper<ChanpinxinxiEntity> ew = new EntityWrapper<ChanpinxinxiEntity>();

        PageUtils page = chanpinxinxiService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, chanpinxinxi), params), params));
        return R.ok().put("data", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/lists")
    public R list(ChanpinxinxiEntity chanpinxinxi) {
        EntityWrapper<ChanpinxinxiEntity> ew = new EntityWrapper<ChanpinxinxiEntity>();
        ew.allEq(MPUtil.allEQMapPre(chanpinxinxi, "chanpinxinxi"));
        return R.ok().put("data", chanpinxinxiService.selectListView(ew));
    }

    /**
     * 查询
     */
    @RequestMapping("/query")
    public R query(ChanpinxinxiEntity chanpinxinxi) {
        EntityWrapper<ChanpinxinxiEntity> ew = new EntityWrapper<ChanpinxinxiEntity>();
        ew.allEq(MPUtil.allEQMapPre(chanpinxinxi, "chanpinxinxi"));
        ChanpinxinxiView chanpinxinxiView = chanpinxinxiService.selectView(ew);
        return R.ok("查询农产品信息成功").put("data", chanpinxinxiView);
    }

    /**
     * 后端详情
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        ChanpinxinxiEntity chanpinxinxi = chanpinxinxiService.selectById(id);
        ChanpinxinxiView view = new ChanpinxinxiView();
        BeanUtils.copyProperties(chanpinxinxi, view);
        if (chanpinxinxi.getGongyingshangId() != null) {
            view.setGongyingshangName(gongyingshangService.selectById(chanpinxinxi.getGongyingshangId()).getGongyingshangmingcheng());
        }
        return R.ok().put("data", view);
    }

    /**
     * 前端详情
     */
    @IgnoreAuth
    @RequestMapping("/detail/{id}")
    public R detail(@PathVariable("id") Long id) {
        ChanpinxinxiEntity chanpinxinxi = chanpinxinxiService.selectById(id);


        chanpinxinxi.setXiangqing(chanpinxinxi.getXiangqing().concat("<p>物流信息：</p>").concat("<p>").concat(baseMapper.selectwuliu(chanpinxinxi.getChanpinbianhao()).concat("<p>")));
        return R.ok().put("data", chanpinxinxi);
    }


    /**
     * 后端保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody ChanpinxinxiEntity chanpinxinxi, HttpServletRequest request) {
        chanpinxinxi.setId(new Date().getTime() + new Double(Math.floor(Math.random() * 1000)).longValue());
        //ValidatorUtils.validateEntity(chanpinxinxi);
        chanpinxinxiService.insert(chanpinxinxi);
        return R.ok();
    }

    /**
     * 前端保存
     */
    @RequestMapping("/add")
    public R add(@RequestBody ChanpinxinxiEntity chanpinxinxi, HttpServletRequest request) {
        chanpinxinxi.setId(new Date().getTime() + new Double(Math.floor(Math.random() * 1000)).longValue());
        //ValidatorUtils.validateEntity(chanpinxinxi);
        chanpinxinxiService.insert(chanpinxinxi);
        return R.ok();
    }


    /**
     * 修改
     */
    @RequestMapping("/update")
    @Transactional
    public R update(@RequestBody ChanpinxinxiEntity chanpinxinxi, HttpServletRequest request) {
        //ValidatorUtils.validateEntity(chanpinxinxi);
        chanpinxinxiService.updateById(chanpinxinxi);//全部更新
        return R.ok();
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        chanpinxinxiService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 提醒接口
     */
    @RequestMapping("/remind/{columnName}/{type}")
    public R remindCount(@PathVariable("columnName") String columnName, HttpServletRequest request,
                         @PathVariable("type") String type, @RequestParam Map<String, Object> map) {
        map.put("column", columnName);
        map.put("type", type);

        if (type.equals("2")) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            Date remindStartDate = null;
            Date remindEndDate = null;
            if (map.get("remindstart") != null) {
                Integer remindStart = Integer.parseInt(map.get("remindstart").toString());
                c.setTime(new Date());
                c.add(Calendar.DAY_OF_MONTH, remindStart);
                remindStartDate = c.getTime();
                map.put("remindstart", sdf.format(remindStartDate));
            }
            if (map.get("remindend") != null) {
                Integer remindEnd = Integer.parseInt(map.get("remindend").toString());
                c.setTime(new Date());
                c.add(Calendar.DAY_OF_MONTH, remindEnd);
                remindEndDate = c.getTime();
                map.put("remindend", sdf.format(remindEndDate));
            }
        }

        Wrapper<ChanpinxinxiEntity> wrapper = new EntityWrapper<ChanpinxinxiEntity>();
        if (map.get("remindstart") != null) {
            wrapper.ge(columnName, map.get("remindstart"));
        }
        if (map.get("remindend") != null) {
            wrapper.le(columnName, map.get("remindend"));
        }


        int count = chanpinxinxiService.selectCount(wrapper);
        return R.ok().put("count", count);
    }


}
